const axios = require('axios');
const db = require("../db/mysql");
const pm2 = require('pm2-api');


/**
 * 获取IP地理信息
 * @param {*} ctx 
 * @returns 
 */
const getIpData = async (ctx) => {
    try {
        // 获取IP（处理代理情况）
        const ip = ctx.request.headers['x-forwarded-for'] || ctx.request.ip;
        // 调用IP-API获取地理信息
        const response = await axios.get(`http://ip-api.com/json/${ip}`);
        const ipData = response.data;
        // 如果API返回失败
        if (ipData.status !== 'success') {
            ctx.body = {
                code: 500,
                message: 'IP查询失败: ' + (ipData.message || '未知错误'),
                data: null
            };
            return;
        }
        ctx.body = {
            code: 200,
            message: 'IP查询成功',
            data: ipData
        }
    } catch (err) {
        ctx.body = {
            code: 500,
            message: 'IP查询失败',
            data: null,
            error: err
        };
    }
};
const healthCheck = async (ctx) => {
    ctx.body = { code: 200, message: 'get请求访问正常', data: 'Hello Koa!' + ctx.request.ip };
}
const healthCheckPost = async (ctx) => {
    ctx.body = { code: 200, message: 'post请求访问正常', data: 'Hello Koa!' + ctx.request.ip };
}


// 获取pm2列表
const pm2List = async (ctx) => {
    try {
    const list = await pm2.list();
    
    // 获取更详细的进程信息
    const detailedList = await Promise.all(list.map(async (proc) => {
      const monit = await pm2.describe(proc.pm_id);
      return {
        id: proc.pm_id,
        name: proc.name,
        pid: proc.pid,
        status: proc.pm2_env.status,
        uptime: proc.pm2_env.pm_uptime,
        restart: proc.pm2_env.restart_time,
        cpu: monit.monit.cpu,
        memory: monit.monit.memory,
        exec_mode: proc.pm2_env.exec_mode,
        instances: proc.pm2_env.instances,
        version: proc.pm2_env.version,
        path: proc.pm2_env.pm_cwd,
        script: proc.pm2_env.pm_exec_path
      };
    }));
    
    ctx.body = {
      code: 200,
      data: detailedList
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '获取PM2列表失败',
      error: error.message
    };
  }
}
module.exports = { getIpData, healthCheck, healthCheckPost,pm2List };
